package com.syt.hospital.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.syt.exception.SYTException;
import com.syt.hospital.repository.ScheduleRepository;
import com.syt.hospital.service.DepartmentService;
import com.syt.hospital.service.HospitalService;
import com.syt.hospital.service.HospitalSetService;
import com.syt.hospital.service.ScheduleService;
import com.syt.model.hospital.BookingRule;
import com.syt.model.hospital.Department;
import com.syt.model.hospital.Hospital;
import com.syt.model.hospital.Schedule;
import com.syt.result.ResultCodeEnum;
import com.syt.vo.hospital.BookingScheduleRuleVo;
import com.syt.vo.hospital.ScheduleOrderVo;
import com.syt.vo.hospital.ScheduleQueryVo;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: xxx
 * @Date: 2023/2/13 21:34
 * @Description: 排班
 */
@Service
public class ScheduleServiceImpl implements ScheduleService {

    @Autowired
    private ScheduleRepository scheduleRepository;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private HospitalSetService hospitalSetService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private HospitalService hospitalService;

    //更新排班数据 用于MQ操作
    @Override
    public void updateSchedule(Schedule schedule) {
      schedule.setUpdateTime(new Date());
      scheduleRepository.save(schedule);

    }

    /**
     * 根据排班id获取预约下单数据
     * @param scheduleId
     * @return
     */
    @Override
    public ScheduleOrderVo getScheduleOrder(String scheduleId) {
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        //排班信息
        Schedule schedule = scheduleRepository.findById(scheduleId).get();
        if (schedule==null){
            throw new SYTException(ResultCodeEnum.DATA_ERROR);
        }
        //获取医院信息
        Hospital hospital = hospitalService.getHospitalByHoscode(schedule.getHoscode());
        if (hospital==null){
            throw new SYTException(ResultCodeEnum.DATA_ERROR);
        }
        //获取预约规则信息
        BookingRule bookingRule = hospital.getBookingRule();
        if (bookingRule==null){
            throw new SYTException(ResultCodeEnum.DATA_ERROR);
        }

        scheduleOrderVo.setHoscode(schedule.getHoscode());
        scheduleOrderVo.setHosname(hospitalService.getHospName(schedule.getHoscode()));
        scheduleOrderVo.setDepcode(schedule.getDepcode());
        scheduleOrderVo.setDepname(departmentService.getDepName(schedule.getHoscode(), schedule.getDepcode()));
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
        scheduleOrderVo.setTitle(schedule.getTitle());
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        scheduleOrderVo.setAmount(schedule.getAmount());


        //退号截止天数 （如：就诊前一天为-1，当天为0）
        int quitDay = bookingRule.getQuitDay();
        DateTime quitTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());

        //预约开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());

        //预约截止时间
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());

        //当天停止挂号时间
        DateTime stopTime= this.getDateTime(new Date(),bookingRule.getStopTime());
        scheduleOrderVo.setStopTime(stopTime.toDate());

        return scheduleOrderVo;
    }

    /**
     * 根据排班id获取排班数据
     * @param scheduleId
     * @return
     */
    @Override
    public Schedule getScheduleById(String scheduleId) {
        return scheduleRepository.findById(scheduleId).get();
    }

    /**
     * 获取可预约排班数据
     * @param page
     * @param limit
     * @param hoscode
     * @param depcode
     * @return
     */
    @Override
    public Map<String,Object> getBookingScheduleRule(Integer page, Integer limit, String hoscode, String depcode) {

        Map<String,Object> result=new HashMap<>();
        //根据预约规则
        //根据医院编号获取预约规则
        Hospital hospital= hospitalSetService.getByHoscode(hoscode);
        if (hospital==null){
            throw new SYTException(ResultCodeEnum.DATA_ERROR);
        }
        BookingRule bookingRule = hospital.getBookingRule();

        //获取可预约日期排班分页数据
       Page pageList=this.getListDate(page,limit,bookingRule);
        //当前可预约日期
        List<Date> dateList = pageList.getRecords();
        //获取可预约日期科室剩余预约数
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode).and("workDate").in(dateList);
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")//分组字段
                        .first("workDate").as("workDate")//别名
                        .count().as("docCount")//统计
                        .sum("availableNumber").as("availableNumber")//求和
                        .sum("reservedNumber").as("reservedNumber")//求和
        );
        AggregationResults<BookingScheduleRuleVo> aggregationResults = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> scheduleRuleVoList = aggregationResults.getMappedResults();
        //获取剩余科室预约数

        //合并数据 将数据ScheduleVo根据"安排日期"合并到BookingRuleVo
        Map<Date, BookingScheduleRuleVo> scheduleVoMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(scheduleRuleVoList)){
            scheduleRuleVoList.stream().collect(Collectors.toMap(BookingScheduleRuleVo::getWorkDate, BookingScheduleRuleVo->BookingScheduleRuleVo));
        }

        //获取可预约排班规则
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList=new ArrayList<>();
        for (int i = 0,len = dateList.size(); i < len; i++) {
            Date date = dateList.get(i);
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(date);
            if (null==bookingScheduleRuleVo){ //等于空表示当天没有排班医生
                 bookingScheduleRuleVo = new BookingScheduleRuleVo();
                 bookingScheduleRuleVo.setDocCount(0);//就诊医生人数
                 bookingScheduleRuleVo.setAvailableNumber(-1); //科室剩余预约数 -1表示无号
            }
            bookingScheduleRuleVo.setWorkDate(date);
            bookingScheduleRuleVo.setWorkDateMd(date);
            //计算当前预约日期为周几
            String dayOfWeek = this.getDayOfWeek(new DateTime(date));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);

            //最后一页最后一条记录为即将预约 状态 0:正常 1:即将放号 -1:当天已停止挂号
            if (i==1&&page==pageList.getPages()){
               bookingScheduleRuleVo.setStatus(1);
            }else {
                bookingScheduleRuleVo.setStatus(0);
            }
            //当天预约时间若过了停号时间，不能预约
            if (i==0&&page==1){
              DateTime stopTime=  this.getDateTime(new Date(),bookingRule.getStopTime());
              if (stopTime.isBeforeNow()){
                  bookingScheduleRuleVo.setStatus(-1);//停止预约
              }
            }
            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);

        }

        result.put("bookingScheduleList", bookingScheduleRuleVoList);//可预约日期规则数据
        result.put("total", pageList.getTotal());
        Map<String, String> baseMap = new HashMap<>();//其他基础数据
        baseMap.put("hosname", hospitalService.getHospName(hoscode));//医院名称
        Department department = departmentService.getDepartment(hoscode, depcode);//科室
        baseMap.put("bigname", department.getBigname());//大科室名称
        baseMap.put("depname", department.getDepname()); //科室名称
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));//月
        baseMap.put("releaseTime", bookingRule.getReleaseTime());//放号时间
        baseMap.put("stopTime", bookingRule.getStopTime());//停号时间
        result.put("baseMap", baseMap);

        return result;
    }

    /**
     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     */
    private DateTime getDateTime(Date date, String stopTime) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " " + stopTime;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }

    //获取可预约日期排班分页数据
    private Page getListDate(Integer page, Integer limit, BookingRule bookingRule) {
        //当天放号时间
        DateTime releaseTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        //预约周期
        int cycle = bookingRule.getCycle();
        //如果当天放号时间已过，则预约周期后一天为即将放号时间，周期加1
        if (releaseTime.isBeforeNow()) cycle += 1;
        //可预约所有日期，最后一天显示即将放号倒计时
        List<Date> dateList = new ArrayList<>();
        for (int i = 0; i < cycle; i++) {
            //计算当前预约日期
            DateTime curDateTime = new DateTime().plusDays(i);
            String dateString = curDateTime.toString("yyyy-MM-dd");
            dateList.add(new DateTime(dateString).toDate());
        }
        //日期分页，由于预约周期不一样，页面一排最多显示7天数据，多了就要分页显示
        List<Date> pageDateList = new ArrayList<>();
        int start = (page - 1) * limit;
        int end = (page - 1) * limit + limit;
        if (end > dateList.size()) end = dateList.size();
        for (int i = start; i < end; i++) {
            pageDateList.add(dateList.get(i));
        }
        Page<Date> iPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page(page, 7, dateList.size());
        iPage.setRecords(pageDateList);
        return iPage;
    }

    /**
     * 根据医院编号、科室编号和工作日期
     * 查询排班详细信息
     * @param hoscode
     * @param depcode
     * @param workDate
     * @return
     */
    @Override
    public List<Schedule> getScheduleDetails(String hoscode, String depcode, String workDate) {
       //根据参数查询 mongoDB
       List<Schedule> scheduleList=
               scheduleRepository.findScheduleByHoscodeAndDepcodeAndWorkDate(hoscode, depcode,new DateTime(workDate).toDate());
       //得到list集合遍历，向设置其他值 医院名称 科室名称 日期对应星期
        scheduleList.stream().forEach(item->{
            this.packageSchedule(item);
        });
        return scheduleList;
    }

    //封装排班详情其他值 医院名称 科室名称 日期对应星期
    private void packageSchedule(Schedule schedule) {
        //设置医院名称
        schedule.getParam().put("hosname", hospitalSetService.getHospName(schedule.getHoscode()));
        //设置科室名称
        schedule.getParam().put("depname", departmentService.getDepName(schedule.getHoscode(),schedule.getDepcode()));
        //设置日期对应星期
        schedule.getParam().put("dayOfWork", this.getDayOfWeek(new DateTime(schedule.getWorkDate())));
    }

    /**
     * 根据医院编号和科室编号，查询医院排班规则数据
     * 查询医院排班规则数据
     * @param page
     * @param limit
     * @param hoscode
     * @param depcode
     * @return
     */
    @Override
    public Map<String, Object> getScheduleRule(int page, int limit, String hoscode, String depcode) {
        //1、根据医院编号 和 科室编号 查询
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);

        //2、根据工作日workDate日期进行分组
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),//匹配条件
                Aggregation.group("workDate")//分组字段
                .first("workDate").as("workDate")
                //3、统计号源数量
                .count().as("docCount")
                .sum("reservedNumber").as("reservedNumber")
                .sum("availableNumber").as("availableNumber"),
                //4、排序
                Aggregation.sort(Sort.Direction.DESC,"workDate"),
                //5、实现分页
                Aggregation.skip((page-1)*limit),
                Aggregation.limit(limit)
        );
        //调用方法，最终执行
        AggregationResults<BookingScheduleRuleVo> aggregateResults = mongoTemplate.
                aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = aggregateResults.getMappedResults();

        //分组查询的总记录数
        Aggregation totalAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );

        AggregationResults<BookingScheduleRuleVo> totalAggregateResults =
                mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);
        int total = totalAggregateResults.getMappedResults().size();//总记录数

        //把日期对应星期获取
        for (BookingScheduleRuleVo bookingScheduleRuleVo :bookingScheduleRuleVoList){
            Date workDate = bookingScheduleRuleVo.getWorkDate();
            String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
        }

        //设置最终数据，进行返回
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("total", total);
        result.put("bookingScheduleRuleVoList", bookingScheduleRuleVoList);

        //获取医院名称
        String hospName= hospitalSetService.getHospName(hoscode);
        //其他基础数据
        HashMap<String, String> baseMap = new HashMap<>();
        baseMap.put("hospName",hospName);

        result.put("baseMap", baseMap);


        return result;
    }


    /**
     * 根据日期获取周几数据
     * @param dateTime
     * @return
     */
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }

    /**
     * 删除排班
     * @param hoscode
     * @param hosScheduleId
     */
    @Transactional
    @Override
    public void remove(String hoscode, String hosScheduleId) {
        //先查询是否存在，存在删除，不存在提示
        Schedule schedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        System.out.println("schedule"+schedule);
        if (schedule!=null){
            scheduleRepository.deleteById(schedule.getId());
        }
    }

    /**
     * 查询排班数据并分页
     *
     * @param page
     * @param limit
     * @param scheduleQueryVo
     * @return
     */
    @Override
    public org.springframework.data.domain.Page<Schedule> findPageDepartment(int page, int limit, ScheduleQueryVo scheduleQueryVo) {
        //创建pageable对象 设置分页
        PageRequest pageable = PageRequest.of(page-1, limit);

        //创建Example对象 设置条件
        Schedule schedule = new Schedule();
        BeanUtils.copyProperties(scheduleQueryVo, schedule);
        schedule.setIsDeleted(0);
        schedule.setStatus(1);

        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        Example<Schedule> example = Example.of(schedule, matcher);

        org.springframework.data.domain.Page<Schedule> all = scheduleRepository.findAll(example, pageable);
        return (org.springframework.data.domain.Page<Schedule>) all;
    }

    /**
     * 上传排班接口
     *
     * @param paramMap
     */
    @Transactional
    @Override
    public void save(Map<String, Object> paramMap) {
       //paramMap 转换成 Department 对象
        String paramMapString = JSONObject.toJSONString(paramMap);
        Schedule schedule = JSONObject.parseObject(paramMapString, Schedule.class);

        //根据医院编号和科室编号查询和排班编号
        Schedule scheduleExist = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());

        //判断存在修改，不存在添加mongoDB
        if (scheduleExist != null) {
            scheduleExist.setUpdateTime(new Date());
            scheduleExist.setIsDeleted(0);
            scheduleExist.setStatus(1);
            scheduleRepository.save(scheduleExist);
        } else {
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            schedule.setStatus(1);
             scheduleRepository.save(schedule);
        }
    }



}
